from drf_yasg.utils import swagger_auto_schema
from rest_framework.viewsets import GenericViewSet

from account.serializers import LoginSerializer, LoginResponseSerializer, TestSerializer, TestResponseSerializer
from account.services import AccountService
from utils.addons.responses import SuccessResponse, FailedResponse
from utils.decorators.common import add_attr
from utils.handlers.exception import BaseExceptions


class LoginViewSet(GenericViewSet):
    serializer_class = LoginSerializer
    permission_classes = []
    authentication_classes = []

    @swagger_auto_schema(
        responses={200: LoginResponseSerializer()},
    )
    @add_attr(risk_level=1)
    def create(self, request):
        # 校验参数是否合法
        _serializer = self.get_serializer(data=request.data)
        _serializer.is_valid(raise_exception=True)
        # 获取用户信息
        response = _serializer.validated_data
        tokens = response.get('tokens')
        ret = SuccessResponse(response)

        # 设置cookie, 有效期为30天
        ret.set_cookie('access', tokens['access'], max_age=24 * 60 * 60)
        ret.set_cookie('refresh', tokens['refresh'], max_age=30 * 24 * 60 * 60)

        # 刷新过期token的黑名单
        AccountService.flush_expired_tokens()
        return ret

class TestViewSet(GenericViewSet):
    serializer_class = TestSerializer

    @swagger_auto_schema(
        responses={200: TestResponseSerializer()},
    )
    def create(self, request):
        _serializer = self.get_serializer(data=request.data)
        _serializer.is_valid(raise_exception=True)
        response = _serializer.validated_data
        return SuccessResponse(response)